<template>
  <div class="app-container">
    讲师添加
    <el-form label-width="120px">
      <el-form-item label="讲师名称">
        <el-input v-model="teacher.name" />
      </el-form-item>
      <el-form-item label="讲师排序">
        <el-input-number v-model="teacher.sort" controls-position="right" min="0" />
      </el-form-item>
      <el-form-item label="讲师头衔">
        <el-select v-model="teacher.level" clearable placeholder="请选择">
          <!--
            数据类型一定要和取出的json中的一致，否则没法回填
            value使用动态绑定的值，讲师头衔由1 2代替
          -->
          <el-option :value="1" label="高级讲师" />
          <el-option :value="2" label="首席讲师" />
        </el-select>
      </el-form-item>
      <el-form-item label="讲师资历">
        <el-input v-model="teacher.career" />
      </el-form-item>
      <el-form-item label="讲师简介">
        <el-input v-model="teacher.intro" :rows="10" type="textarea" />
      </el-form-item>

      <!-- 讲师头像 -->
      <el-form-item label="讲师头像">
          <el-upload
                    class="avatar-uploader"
                     :action="BASE_API+'/eduoss/fileoss'"
                     :show-file-list="true"
                     :on-success="handleAvatarSuccess"
                     :on-error="handleAvatarError"
                     :before-upload="beforeAvatarUpload">
              <img v-if="teacher.avatar" :src="teacher.avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" plain="true" type="primary" @click="saveOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
//引入调用teacher.js文件
import teacherApi from '@/api/edu/teacher'
//引入上传头像的功能组件
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
export default {
  components:{ImageCropper,PanThumb},
  data(){
    return{
      teacher:{
        name:'',
        sort:0,
        level:1,
        career:'',
        intro:'',
        avatar:'',
      },
      imagecropperShow: false, //上传弹框组件是否显示
      imagecropperKey: 0, //上传组件唯一标识
      BASE_API: process.env.BASE_API, //获取dev.env.js里面地址
      saveBtnDisabled: false //保存按钮是否禁用
    }
  },
  //监听
  watch:{
    $route(to,from){//路由变化
      this.init()
    }
  },
  created(){
    this.init()
  },
  methods:{
    // 文件上传成功
    handleAvatarSuccess(response, file) {
      if (response.success) {
          console.log(response.data)
          this.teacher.avatar = response.data.url
          // 强制重新渲染
          this.$forceUpdate()
        } else {
          this.$message.error('上传失败! （非20000）')
        }    
    },
    // 文件上传失败（http)
    handleAvatarError() {
        this.$message.error('上传失败! （http失败）')
    },
    // 上传校验
    beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isGIF = file.type === 'image/gif';
        const isPNG = file.type === 'image/png';
        const isBMP = file.type === 'image/bmp';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG && !isGIF && !isPNG && !isBMP) {
            this.common.errorTip('上传图片必须是JPG/GIF/PNG/BMP 格式!');
        }
        if (!isLt2M) {
            this.common.errorTip('上传图片大小不能超过 2MB!');
        }
        return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
    },
    //初始化
    init(){
      //判断路径是否有id值
      //有id为修改
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.getInfo(id)
      }else{//没有id值，做添加
        //清空表单
        this.teacher={}
      }
    },
    //根据id查询讲师
    getInfo(id){
      teacherApi.getTeacherInfo(id)
        .then(response=>{
          this.teacher = response.data.teacher
        })
    },
    //添加或修改
    saveOrUpdate(){
      //根据id判断是修改还是添加
      if(!this.teacher.id){
        this.saveTeacher() //添加
      }else{
        this.updateTeacher()  //修改
      }
    },
    //根据id修改讲师
    updateTeacher(){
      teacherApi.updateTeacherInfo(this.teacher)
        .then(response=>{
          //提示信息    
          this.$message({
            type:'success',
            message:'修改成功'
          })
          //回到列表(路由跳转)
          this.$router.push({path:'/teacher/table'})
        })
    },
    //添加讲师的方法
    saveTeacher(){
      teacherApi.addTeacher(this.teacher)
        .then(response=>{//添加成功
          //提示信息    
          this.$message({
            type:'success',
            message:'添加成功'
          })
          //回到列表(路由跳转)
          this.$router.push({path:'/teacher/table'})
        })
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar-uploader img {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>